/**
* @function Get 获取当前时间
*/
function getTime() {
	var myDate = new Date();
	//获取当前年
	var year=myDate.getFullYear();
	
	//获取当前月
	var month=myDate.getMonth()+1;
	if(month<10) month = '0' + month;
	
	//获取当前日
	var date=myDate.getDate();
	if(date<10) date = '0' + date;
	
	var h=myDate.getHours(); //获取当前小时数(0-23)
	if(h<10) h = '0' + h;
	
	var m=myDate.getMinutes(); //获取当前分钟数(0-59)
	if(m<10) m = '0' + m;
	
	var s=myDate.getSeconds();
	if(s<10) s = '0' + s;
	
	var now=year+'-'+month+"-"+date+" "+h+':'+m+":"+s;
	return now;
}


/**
 * textarea高度自适应
 */
$(function () {
    $('.content').flexText();
});

/**
 * textarea限制字数
 * @param {textarea限制字数} t
 */
function keyUP(t){
    var len = $(t).val().length;
    if(len > 139){
        $(t).val($(t).val().substring(0,140));
    }
}

/**
 * 点击评论创建评论条
 */
$('.commentAll').on('click','.plBtn',function(){
    // 获取输入内容
    var oSize = $(this).siblings('.flex-text-wrap').find('.comment-input').val();
   
    // 评论内容不为空，动态创建评论模块
    if(oSize.replace(/(^\s*)|(\s*$)/g, "") != ''){
        // 后台评论入库
        var sort = 0;
        saveComment(sort, $(this), oSize);
    } else {
        alert('评论不能为空！');
    }
});

/**
 * 评论留言及回复存入数据库
 * @param _this 传$(this)
 * @param content 评论内容
 * @param user_id 评论者
 * @param father_id 被评论的评论id
 * @param to_id 被评论者的id
 */
function saveComment(sort, _this, content, father_id, to_id, father_nickname, father_content) {
	if(father_id == undefined) {
		father_id=null;
	}
	
	if(to_id == undefined) {
		to_id=null;
	}
	
	var bookId = $("#bookId").val();
	
    $.ajax({
        url:'../comment/review',
        type:'POST',
        data:{bookId:bookId,blob:content,fatherId:father_id,toId:to_id},
        success: function(result) {
        	if(result.rspCode=="000000"){
        		if(result.data) {
                    // sort=0 主评论 sort=1 子评论
                    if(sort == 0 ) {
                        addComments(_this, content, result.data.comment_id, result.data.user);
                    } else {
                        addApplyComment(_this, content, result.data.comment_id, father_nickname, father_content,result.data.user);
                    }
                }
        	}else if(result.rspCode=="000109"){
        		alert("请先登录..");
        		location.href="../login";
        	}else if(result.rspCode=="000112"){
        		alert(result.rspMsg);
        	}else if(result.rspCode=="000115"){
        		alert(result.rspMsg);
        	}else{
        		console.log("评论错误...");
        	}
        },
        error: function(err){
            console.log(err);
            console.log('评论失败');
            return false;
        }
    })
}

/**
 * 动态添加评论模块
 * @param _this 传$(this)
 * @param oSize 评论内容
 */
function addComments(_this, oSize, commentId, user) {
    // 获取当前时间
    var now = getTime();
    var oHtml = '';

    oHtml = "<div class='comment-show-con clear-f' commentId="+commentId+">"
            +"<div class='comment-show-con-img fl' style='background-image:url("+user.headImg+")'></div>"
            +"<div class='comment-show-con-list fl clear-f'>"
            +"<div class='pl-text clear-f'>"
            +"<a href='#' class='comment-size-name' userId="+user.id+">"+user.nickname+"：</a>"
            +"<span class='my-pl-con'>&nbsp;"+oSize+"</span>"
            +"</div>"
            +"<div class='date-dz'>"
            +"<span class='date-dz-left fl comment-time'>"+now+"</span>"
            +"<div class='date-dz-right fr comment-pl-block'>"
            +"<a href='javascript:;' class='removeBlock'>删除</a>"
            +"<a href='javascript:;' class='date-dz-pl pl-hf hf-con-block fl'>回复(<i class='z-num'>0</i>)</a>"
            +"<span class='fl date-dz-line'>|</span>"
            +"<a href='javascript:;' class='date-dz-z fl'>"
            +"<i class='date-dz-z-click-red'></i>赞(<i class='z-num'>0</i>)"
            +"</a>"
            +"</div>"
            +"</div>"
            +"<div class='hf-list-con'></div>"
            +"</div>"
            +"</div>";
    
    console.log(oHtml);

    // 前端插入评论
    _this.parents('.reviewArea ').siblings('.comment-show').prepend(oHtml);
    // 清空评论输入框
    _this.siblings('.flex-text-wrap').find('.comment-input').prop('value','').siblings('pre').find('span').text('');
}

/**
 * 点击回复动态创建回复块
 */
$('.comment-show').on('click','.pl-hf',function(){
    // 被评论的评论id
    var father_id = $(this).parents('.comment-show-con').attr('commentId');

    var oThis = $(this);
    // 查询数据库，展示子评论
    $.ajax({
        url: '../comment/getSonComment',
        data:{cid:father_id},
        type: 'get',
        success: function(result) {
            // 如果有子评论则渲染
            if(result.length > 0) {
                showChildComments(oThis, result);
            }
            createCommentArea(oThis);
        },
        error: function(err) {
            console.log(err);
            alert('网络有问题，请稍候再试！');
        }
    })
});

/**
 * 创建回复块
 * @param _this 传入$(this)
 */
function createCommentArea(_this) {
    // 获取回复人的名字
    var fhName = _this.parents('.date-dz-right').parents('.date-dz').siblings('.pl-text').find('.comment-size-name').html();
    // 回复@
    var fhN = '回复@'+fhName;

     var fhHtml ="<div class='hf-con fl'>"
	            +"<textarea class='content comment-input hf-input' placeholder='"+fhN+"' onkeyup='keyUP(this)'></textarea>"
	            +"<a href='javascript:;' class='hf-pl'>评论</a>"
	            +"</div>";
    // 显示回复
    if(_this.is('.hf-con-block')){
        _this.parents('.date-dz-right').parents('.date-dz').append(fhHtml);
        _this.removeClass('hf-con-block');
        $('.content').flexText();
        // input框自动聚焦
        _this.parents('.date-dz-right').siblings('.hf-con').find('.hf-input').val('').focus();
    }else {
        _this.addClass('hf-con-block');
        _this.parents('.date-dz-right').siblings('.hf-con').remove();
        _this.parents('.date-dz').siblings('.hf-list-con').css('display', 'none');
    }
}

/**
 * 点击展开回复展示子评论
 * @param oThis 传入$(this)
 * @param result 子评论结果集
 */
function showChildComments(oThis, result) {
    var oHtml = '';

    for (var i = 0; i < result.length; i++) {
        var content;
        if(result[i].isShow==0){
    		result[i].commentMsg="该评论已被删除";
    	}
        if(result[i].toComment!=null) {
        	var toCommentMsg = result[i].toComment.commentMsg;
        	if(result[i].toComment.isShow==0){
        		toCommentMsg="该评论已被删除";
        	}else if(toCommentMsg.length>40){
        		toCommentMsg = toCommentMsg.substring(0,40) + "......";
        	}
            content = result[i].commentMsg + '&nbsp;&nbsp;&nbsp;//@' + result[i].toComment.user.nickname + '：' + toCommentMsg;
        } else {
            content = result[i].commentMsg;
        }
        oHtml +="<div class='all-pl-con' commentsId="+result[i].id+">"
                +"<div class='pl-text hfpl-text clear-f'>"
                +"    <a href='#' class='comment-size-name' userId="+result[i].userId+">"+result[i].user.nickname+"：</a>"
                +"    <span class='my-pl-con'>"+content+"</span>"
                +"</div>"
                +"<div class='date-dz'>"
                +"    <span class='date-dz-left fl comment-time'>"+result[i].addTime+"</span>"
                +"    <div class='date-dz-right fr comment-pl-block'>";
        
        if(result[i].isCurrentUserComment!=""&&result[i].isCurrentUserComment!=null&&result[i].isShow!=0){
        	oHtml +="        <a href='javascript:;' class='removeBlock'>删除</a>";
        }else{
        	oHtml +="        <a href='javascript:;' class='removeBlock'></a>";
        }
        oHtml +="        <a href='javascript:;' class='date-dz-pl pl-hf hf-con-block fl'>回复(<i class='z-num'>"+result[i].sonComments+"</i>)</a>"
                +"        <span class='fl date-dz-line'>|</span>";
        if(result[i].isCurrentUserLike!=""&&result[i].isCurrentUserLike!=null){
        	oHtml +="        <a href='javascript:;' class='date-dz-z fl date-dz-z-click'>";
		}else{
			oHtml +="        <a href='javascript:;' class='date-dz-z fl'>";
		}
        oHtml +="            <i class='date-dz-z-click-red'></i>赞(<i class='z-num'>"+result[i].likes+"</i>)"
                +"        </a>"
                +"    </div>"
                +"</div>"
                +"</div>";
    }

    oThis.parents('.date-dz').siblings('.hf-list-con').html('').css('display','block').prepend(oHtml);
}


/**
 * 评论回复块创建
 */
$('.comment-show').on('click','.hf-pl',function(){
    //获取输入内容
    var oHfVal = $(this).siblings('.flex-text-wrap').find('.hf-input').val();

    // 被评论的评论id
    var father_id = $(this).parents('.comment-show-con').attr('commentId');

    var to_id;
    var father_nickname;
    var father_content;
    if($(this).parents('.hf-list-con').length > 0) {
        // 评论中被评论的评论id
        to_id = $(this).parents('.all-pl-con').attr('commentsId');
        // 被评论者昵称
        father_nickname = $(this).parents('.date-dz').siblings('.hfpl-text').find('.comment-size-name').html();
        // 被评论的内容
        father_content = $(this).parents('.date-dz').siblings('.hfpl-text').find('.my-pl-con').html();
    }
    
    //获取回复人的名字
    var oHfName = $(this).parents('.hf-con').parents('.date-dz').siblings('.pl-text').find('.comment-size-name').html();

    if(oHfVal.replace(/(^\s*)|(\s*$)/g, "") != ''){
        // 后台数据入库
        var sort = 1;
        if(to_id==""){
        	to_id=null;
        }
        saveComment(sort, $(this), oHfVal, father_id, to_id, father_nickname, father_content);
    } else {
        alert('评论不能为空！');
    }
});

/**
 * 动态添加回复评论模块dom结构
 * @param _this 传${this}
 * @param oHfVal 回复内容
 */
function addApplyComment(_this, oHfVal, commentId, father_nickname, father_content,user) {
    // 获取当前时间
    var now = getTime();
    var oHtml = '';

    // 主评论数量+1
    var curTotalCommentNumber = _this.parents('.comment-show-con-list').children('.date-dz').find('.pl-hf .z-num').html();
    curTotalCommentNumber++;
    _this.parents('.comment-show-con-list ').children('.date-dz').find('.pl-hf .z-num').html(curTotalCommentNumber);
    // 子评论数量+1
    if(_this.parents('.hf-list-con').length > 0) {
        var curChildCommentNumber = _this.parents('.hf-con').siblings('.date-dz-right').find('.pl-hf .z-num').html();
        curChildCommentNumber++;
        _this.parents('.hf-con').siblings('.date-dz-right').find('.pl-hf .z-num').html(curChildCommentNumber);
    }

    var content;
    if(!!father_content) {
        // 统计//@的个数，处理回复显示的内容
        var n=(father_content.split('//@')).length-1;
        var fa_content;
        if(n>0) {
            fa_content = father_content.substring(0, father_content.lastIndexOf('//@'));
        } else {
            fa_content = father_content;
        }
        if(fa_content.length>40){
        	fa_content = fa_content.substring(0,40) + "......";
        }
        content = oHfVal + '&nbsp;&nbsp;&nbsp;//@' + father_nickname + fa_content;
    } else {
        content = oHfVal;
    }

     
    oHtml ="<div class='all-pl-con' commentsId="+commentId+">"
            +"<div class='pl-text hfpl-text clear-f'>"
            +"    <a href='#' class='comment-size-name' userId="+user.id+">"+user.nickname+"：</a>"
            +"    <span class='my-pl-con'>"+content+"</span>"
            +"</div>"
            +"<div class='date-dz'>"
            +"    <span class='date-dz-left fl comment-time'>"+now+"</span>"
            +"    <div class='date-dz-right fr comment-pl-block'>"
            +"        <a href='javascript:;' class='removeBlock'>删除</a>"
            +"        <a href='javascript:;' class='date-dz-pl pl-hf hf-con-block fl'>回复(<i class='z-num'>0</i>)</a>"
            +"        <span class='fl date-dz-line'>|</span>"
            +"        <a href='javascript:;' class='date-dz-z fl'>"
            +"            <i class='date-dz-z-click-red'></i>赞(<i class='z-num'>0</i>)"
            +"        </a>"
            +"    </div>"
            +" </div>"
            +" </div>";

    // 前端插入评论
    _this.parents('.hf-con').parents('.comment-show-con-list').find('.hf-list-con').css('display','block').prepend(oHtml);
    // 清空回复框
    _this.siblings('.flex-text-wrap').find('.comment-input').prop('value','').siblings('pre').find('span').text('');
}


/**
 * 删除评论块
 */
$('.commentAll').on('click','.removeBlock',function(){
	var deleteId;
	var father_id;
    if($(this).parents('.hf-list-con').length > 0) {
        deleteId = $(this).parents('.all-pl-con').attr('commentsId');//属于子评论
        father_id = $(this).parents('.comment-show-con').attr('commentId');
    } else {
        deleteId = $(this).parents('.comment-show-con').attr('commentId');//属于发起评论
    }
    var _this = $(this);
    var oT = $(this).parents('.date-dz-right').parents('.date-dz').parents('.all-pl-con');
    $.ajax({
        url: '/comment/deleteComment',
        type: 'post',
        data: {
        	commentId: deleteId,
        	fatherId:father_id
        },
        success: function(result){
            console.log(result);
            if(result.rspCode=="000000"){
            	if(oT.siblings('.all-pl-con').length >= 1){
                    oT.remove();
                }else {
                	_this.parents('.date-dz-right').parents('.date-dz').parents('.all-pl-con').parents('.hf-list-con').css('display','none')
                    oT.remove();
                }
                _this.parents('.date-dz-right').parents('.date-dz').parents('.comment-show-con-list').parents('.comment-show-con').remove();
            }
        },
        error: function(err) {
            console.log(err);
        }
    });
})

/**
 * 点赞
 */
$('.comment-show').on('click','.date-dz-z',function(){
    var commentId;
    var likeValue;
    if($(this).parents('.hf-list-con').length > 0) {
        commentId = $(this).parents('.all-pl-con').attr('commentsId')
    } else {
        commentId = $(this).parents('.comment-show-con').attr('commentId');
    }
    if($(this).is('.date-dz-z-click')){
    	likeValue = "0";
    }else{
    	likeValue = "1";
    }
    
    var _this = $(this);
    $.ajax({
        url: '../comment/toLike',
        type: 'post',
        data:{commentId:commentId,likeValue:likeValue},
        success: function(result){
        	if(result.rspCode=="000000"){
        		console.log("成功点赞");
        		var zNum = _this.find('.z-num').html();
        	    if(_this.is('.date-dz-z-click')){
        	        zNum--;
        	        _this.removeClass('date-dz-z-click');
        	        _this.find('.z-num').html(zNum);
        	    }else {
        	        zNum++;
        	        _this.addClass('date-dz-z-click');
        	        _this.find('.z-num').html(zNum);
        	    }
        	}else if(result.rspCode=="000109"){
          		alert(result.rspMsg);
          		location.href="../login";
          	}else{
        		console.log("点赞失败");
        	}
        },
        error: function(err) {
            console.log(err);
        }
        
        
    });

    
})